//
//  ActivityEditingViewController.m
//  TimeTracker
//
//  Created by Michael Flakus on 2/21/13.
//  Copyright (c) 2013 Michael Flakus. All rights reserved.
//

#import "ActivityEditingViewController.h"
#import "ActivityDetailViewController.h"


@implementation ActivityEditingViewController

@synthesize activityNameTextField, createCategoryTextField, editedObject, editedPropertyKey, editedPropertyDisplayName, categoryPickerView, sourceController;

#pragma mark -
#pragma mark View lifecycle

- (void)viewDidLoad {
    
	// Set the title to the user-visible name of the field.
	self.title = editedPropertyDisplayName;
    self.view.backgroundColor = [UIColor whiteColor];
	
	// Configure the save and cancel buttons.
	UIBarButtonItem *saveButton = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemSave target:self action:@selector(save)];
	self.navigationItem.rightBarButtonItem = saveButton;
	
	UIBarButtonItem *cancelButton = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemCancel target:self action:@selector(cancel)];
	self.navigationItem.leftBarButtonItem = cancelButton;
    
    // create input fields
    
    // activity name text field
    CGRect frame = CGRectMake(10.0, 20.0, 300.0, 28.0);
    activityNameTextField = [[UITextField alloc] initWithFrame:frame];
    activityNameTextField.borderStyle = UITextBorderStyleRoundedRect;
    activityNameTextField.textColor = [UIColor blackColor];
    activityNameTextField.font = [UIFont systemFontOfSize:17.0];
    //textField.placeholder = @"";
    activityNameTextField.backgroundColor = [UIColor clearColor];
    activityNameTextField.autocorrectionType = UITextAutocorrectionTypeYes;
    activityNameTextField.keyboardType = UIKeyboardTypeDefault;
    activityNameTextField.clearButtonMode = UITextFieldViewModeWhileEditing;
    [self.view addSubview:activityNameTextField];
    
    // new category
    CGRect frame2 = CGRectMake(10.0, 20.0, 300.0, 28.0);
    createCategoryTextField = [[UITextField alloc] initWithFrame:frame2];
    createCategoryTextField.borderStyle = UITextBorderStyleRoundedRect;
    createCategoryTextField.textColor = [UIColor blackColor];
    createCategoryTextField.font = [UIFont systemFontOfSize:17.0];
    createCategoryTextField.backgroundColor = [UIColor clearColor];
    createCategoryTextField.autocorrectionType = UITextAutocorrectionTypeYes;
    createCategoryTextField.keyboardType = UIKeyboardTypeDefault;
    createCategoryTextField.clearButtonMode = UITextFieldViewModeWhileEditing;
    [self.view addSubview:createCategoryTextField];
    
    // load category options from database
    
    NSLog(@"loading categories from database");
    
    // load data from database
    _categoryNames = [[NSMutableArray alloc] init];
    _categoryIds = [[NSMutableArray alloc] init];
    int row = 0;
    int selected_row = 0;
    
    
    // database lookups
    @try {
        
        // connect to db
        
        NSString *docsDir;
        NSArray *dirPaths;
        
        // Get the documents directory
        dirPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
        
        docsDir = dirPaths[0];
        
        // Build the path to the database file
        _databasePath = [[NSString alloc] initWithString: [docsDir stringByAppendingPathComponent: @"TimeTracker.sqlite"]];
        
        NSFileManager *filemgr = [NSFileManager defaultManager];
        
        // check to see if database already exists...
        if ([filemgr fileExistsAtPath: _databasePath ] == YES)
        {
            // open database
            if(!(sqlite3_open([_databasePath UTF8String], &_database) == SQLITE_OK))
            {
                NSLog(@"An error has occured when trying to open the database");
            }
            
            // load all active categories
            
            // add special "New Category" option to picker as the first option
            [_categoryIds addObject:@"0"];
            [_categoryNames addObject:@"Add a New Category..."];
            
            NSString *select_categories = [NSString stringWithFormat:@"SELECT categories.id,categories.name from categories where categories.active = 1 order by categories.name"];
            const char *select_categories_const = [select_categories UTF8String];
            
            sqlite3_stmt *res_categories;
            if(sqlite3_prepare(_database, select_categories_const, -1, &res_categories, NULL) != SQLITE_OK)
            {
                NSLog(@"Problem with prepare statement: %s",select_categories_const);
                NSLog(@"%s Prepare failure '%s' (%1d)", __FUNCTION__, sqlite3_errmsg(_database), sqlite3_errcode(_database));
            }
            else
            {
                while (sqlite3_step(res_categories)==SQLITE_ROW) {
                    
                    NSLog(@"Found a category: %@",[NSString stringWithUTF8String:(char *) sqlite3_column_text(res_categories,1)]);
                    
                    if([_categoryName isEqualToString:[NSString stringWithUTF8String:(char *) sqlite3_column_text(res_categories,1)]])
                    {
                        selected_row = row+1;
                    }
                    
                    [_categoryIds addObject:[NSString stringWithUTF8String:(char *) sqlite3_column_text(res_categories,0)]];
                    [_categoryNames addObject:[NSString stringWithUTF8String:(char *) sqlite3_column_text(res_categories,1)]];
                    
                    
                    row++;
                }
                sqlite3_finalize(res_categories);
            }
        }
        else
        {
            NSLog(@"Error: database could not be found in ActivityEditingViewController");
        }
    }
    
    @catch (NSException *exception) {
        NSLog(@"An exception occured: %@", [exception reason]);
    }
    @finally {
        // close the database connection
        sqlite3_close(_database);
    }

    
    CGRect frame_picker = CGRectMake(0.0, 60.0, 320.0, 400.0);
    categoryPickerView = [[UIPickerView alloc] initWithFrame:frame_picker];   
    categoryPickerView.delegate = self;
    categoryPickerView.showsSelectionIndicator = YES;
    [categoryPickerView selectRow:selected_row inComponent:0 animated:YES];
    [self.view addSubview:categoryPickerView];
    
    
    
}


- (void)viewWillAppear:(BOOL)animated {
	
	[super viewWillAppear:animated];
    
    NSLog(@"property: %@",editedPropertyDisplayName);
    
	// Update user interface according to state.
    if ([editedPropertyDisplayName isEqualToString:@"Category"]) {
        activityNameTextField.hidden = YES;
        createCategoryTextField.hidden = YES;
        categoryPicker.hidden = NO;
    }
	else {
        NSLog(@"show only textfield");
        activityNameTextField.hidden = NO;
        createCategoryTextField.hidden = YES;
        categoryPickerView.hidden = YES;
        activityNameTextField.text = _activityName;
		activityNameTextField.placeholder = self.title;
        [activityNameTextField becomeFirstResponder];
    }
}


#pragma mark -
#pragma mark Save and cancel operations

- (IBAction)save {
	
    // update the current value in the databbase, then return to the previous view
    //NSLog(@"update category with row: %@",_selectedCategoryID);
	//NSLog(@"category name: %@",_categoryNames[[_selectedCategoryID intValue]]);
    //NSLog(@"activity id: %@",_activityID);
    
    // update field
    @try {
        
        // connect to db
        
        NSString *docsDir;
        NSArray *dirPaths;
        
        // Get the documents directory
        dirPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
        
        docsDir = dirPaths[0];
        
        // Build the path to the database file
        _databasePath = [[NSString alloc] initWithString: [docsDir stringByAppendingPathComponent: @"TimeTracker.sqlite"]];
        
        NSFileManager *filemgr = [NSFileManager defaultManager];
        
        // check to see if database already exists...
        if ([filemgr fileExistsAtPath: _databasePath ] == YES)
        {
            // open database
            if(!(sqlite3_open([_databasePath UTF8String], &_database) == SQLITE_OK))
            {
                NSLog(@"An error has occured when trying to open the database");
            }
            
            NSString *update_sql;
            char *errMsg;
            
            if ([editedPropertyDisplayName isEqualToString:@"Category"]) {
                
                if([_selectedCategoryID intValue] == 0)
                {
                    // TODO: display an alert to the user if the provided new category name is blank
                    
                    // New Category needs to be saved first and then assigned to this activity
                    NSString *insert_category = [NSString stringWithFormat:@"INSERT INTO categories (name) VALUES ('%@')",createCategoryTextField.text];
                    const char *insert_category_const = [insert_category UTF8String];
                    if (sqlite3_exec(_database, insert_category_const, NULL, NULL, &errMsg) != SQLITE_OK)
                        NSLog(@"Failed to insert category: %s",errMsg);
                    
                    // lookup id for newly added category
                    NSString *new_category_id = [NSString stringWithFormat:@"select id from categories where name = '%@'",createCategoryTextField.text];
                    const char *new_category_id_const = [new_category_id UTF8String];
                    
                    sqlite3_stmt *res_new_category_id;
                    if(sqlite3_prepare(_database, new_category_id_const, -1, &res_new_category_id, NULL) != SQLITE_OK)
                    {
                        NSLog(@"Problem with prepare statement: %s",new_category_id_const);
                        NSLog(@"%s Prepare failure '%s' (%1d)", __FUNCTION__, sqlite3_errmsg(_database), sqlite3_errcode(_database));
                    }
                    else
                    {
                        NSLog(@"query: %s",new_category_id_const);
                        
                        while (sqlite3_step(res_new_category_id)==SQLITE_ROW) {
                            update_sql = [NSString stringWithFormat:@"update activities set category_id = '%@' where id like '%@'",[NSString stringWithUTF8String:(char *) sqlite3_column_text(res_new_category_id,0)],_activityID];
                            break;
                        }
                        
                        sqlite3_finalize(res_new_category_id);
                    }
                    
                } else {
                    update_sql = [NSString stringWithFormat:@"update activities set category_id = '%@' where id like '%@'",_selectedCategoryID,_activityID];
                }
            } else {
                update_sql = [NSString stringWithFormat:@"update activities set activity_name = '%@' where id like '%@'",activityNameTextField.text,_activityID];
            }
             
            const char *update_const = [update_sql UTF8String];
            sqlite3_stmt *res_update;
            if(sqlite3_prepare(_database, update_const, -1, &res_update, NULL) != SQLITE_OK)
            {
                NSLog(@"Problem with prepare statement: %s",update_const);
                NSLog(@"%s Prepare failure '%s' (%1d)", __FUNCTION__, sqlite3_errmsg(_database), sqlite3_errcode(_database));
            }
            else
            {
                NSLog(@"query: %s",update_const);
                if(SQLITE_DONE != sqlite3_step(res_update))
                    NSAssert1(0, @"Error while updating. '%s'", sqlite3_errmsg(_database));
                
                sqlite3_finalize(res_update);
            }
        }
        else
        {
            NSLog(@"Error: database could not be found in ActivityEditingViewController");
        }
    }
    
    @catch (NSException *exception) {
        NSLog(@"An exception occured: %@", [exception reason]);
    }
    @finally {
        // close the database connection
        sqlite3_close(_database);
    }

    [self.navigationController popViewControllerAnimated:YES];
}


- (IBAction)cancel {
    // return to the previous view, without saving
    [self.navigationController popViewControllerAnimated:YES];
}



#pragma mark -
#pragma mark Category Picker operations

- (void)pickerView:(UIPickerView *)pickerView didSelectRow: (NSInteger)row inComponent:(NSInteger)component {
    // Handle the selection
    NSLog(@"new category selected %d",row);
    
    if(row == 0)
    {
        NSLog(@"special NEW option selected");
        _selectedCategoryID = @"0";
        createCategoryTextField.hidden = NO;
        [createCategoryTextField becomeFirstResponder];
    }
    else
    {
        _selectedCategoryID = _categoryIds[row];
        //NSLog(@"selected category id: %@",_categoryIds[row]);
        //NSLog(@"selected category name: %@",_categoryNames[row]);
        createCategoryTextField.hidden = YES;
        [createCategoryTextField resignFirstResponder];
    }
}

// tell the picker how many rows are available for a given component
- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component {
        return _categoryIds.count;
}

// tell the picker how many components it will have
- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView {
    return 1;
}

// tell the picker the title for a given component
- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component {
    
    // use row id to display associated label
    
    NSString *title;
    title = _categoryNames[row];
    
    return title;
}

// tell the picker the width of each row for a given component
- (CGFloat)pickerView:(UIPickerView *)pickerView widthForComponent:(NSInteger)component {
    int sectionWidth = 300;
    
    return sectionWidth;
}





@end

